import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { randomUUID } from 'crypto';
import { Server } from 'ws';
import { Socket } from 'socket.io';

@WebSocketGateway(80)
export class EventsGateway {
  /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
  private static onlineCount = 0;
  /**users的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
  private static users = new Map();

  @WebSocketServer()
  server: Server;

  /**
   * 链接成功
   */
  handleConnection(client: Server) {
    console.log(Socket);
    EventsGateway.onlineCount += 1;
    const socketId = randomUUID();
    EventsGateway.users.set(socketId, client);
  }

  /**
   * 断开链接
   */
  handleDisconnect(client: Server) {
    EventsGateway.onlineCount -= 1;
  }

  @SubscribeMessage('events')
  onEvent(client: any, data: any) {
    return { event: 'events', data: 'PING' };
  }
}
